<template>
    <div class="docs-section">
        <div class="docs-header">
            <h3 class="docs-title">古籍查询</h3>
        </div>
        
        <!-- 书籍封面滑动区域 -->
        <BookCoversSlider
            v-if="Object.keys(booksData).length > 0"
            :books-data="booksData"
            :selected-book-id="selectedBookId"
            @select-book="handleSelectBook"
        />

        <!-- 调候用神提示（仅穷通宝鉴显示） -->
        <TiaohouYongshen
            v-if="selectedBookId === 'b01' && baziString && zangganArray"
            :bazi="baziString"
            :zanggan="zangganArray"
        />

        <!-- 标题tab滑动区域 -->
        <TitleTabsSlider
            v-if="selectedBookTitles.length > 0"
            :titles="selectedBookTitles"
            :selected-title="selectedTitle"
            @select-title="handleSelectTitle"
        />

        <!-- 内容展示区域 -->
        <ContentDisplay
            v-if="contentData.length > 0"
            :content-data="sortedContentData"
        />

        <!-- 加载状态 -->
        <div v-if="docsLoading" class="loading-container">
            <van-loading type="spinner" color="#3b82f6">加载中...</van-loading>
        </div>

        <!-- 空状态 -->
        <div v-if="!docsLoading && Object.keys(booksData).length === 0" class="empty-container">
            <p class="empty-text">暂无书籍数据</p>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, withDefaults } from 'vue'
import { showToast } from 'vant'
import { docsApi, type DocsContentItem } from '@/api/bazi'
import BookCoversSlider from './book_covers_slider.vue'
import TitleTabsSlider from './title_tabs_slider.vue'
import ContentDisplay from './content_display.vue'
import TiaohouYongshen from './tiaohou_yongshen.vue'

interface Props {
    bazi: string // 八字字符串
    zanggan?: Array<Array<{ stem: string }>> // 藏干数组，可选
}

const props = withDefaults(defineProps<Props>(), {
    zanggan: () => []
})

// 确保 bazi 是字符串类型
const baziString = computed(() => props.bazi || '')

// 藏干数组
const zangganArray = computed(() => props.zanggan || [])

// 书籍查询相关状态
const booksData = ref<Record<string, string[]>>({})
const selectedBookId = ref<string>('')
const selectedTitle = ref<string>('')
const contentData = ref<DocsContentItem[]>([])
const docsLoading = ref(false)

// 当前选中的书籍标题列表
const selectedBookTitles = computed(() => {
    if (!selectedBookId.value || !booksData.value[selectedBookId.value]) {
        return []
    }
    return booksData.value[selectedBookId.value] || []
})

// 按orderNum排序的内容数据
const sortedContentData = computed(() => {
    return [...contentData.value].sort((a, b) => {
        const orderA = a.orderNum ?? 0
        const orderB = b.orderNum ?? 0
        return orderA - orderB
    })
})

// 查询书籍列表
const queryBooks = async () => {
    const bazi = baziString.value
    if (!bazi || bazi.length !== 8) {
        return
    }
    
    docsLoading.value = true
    try {
        const response = await docsApi.queryDocs(bazi)
        const data = response.data as any
        
        // 过滤掉空数组的书籍
        const filteredBooks: Record<string, string[]> = {}
        Object.keys(data).forEach(key => {
            const titles = data[key]
            if (titles && Array.isArray(titles) && titles.length > 0) {
                filteredBooks[key] = titles
            }
        })
        
        booksData.value = filteredBooks
        
        // 默认选中第一个书籍的第一个title
        const firstBookKey = Object.keys(filteredBooks)[0]
        if (firstBookKey) {
            const firstTitles = filteredBooks[firstBookKey]
            if (firstTitles && firstTitles.length > 0) {
                const firstTitle = firstTitles[0]
                if (firstTitle) {
                    selectedBookId.value = firstBookKey
                    selectedTitle.value = firstTitle
                    // 自动加载第一个title的内容
                    loadContent(firstBookKey, firstTitle)
                }
            }
        }
    } catch (error) {
        console.error('查询书籍失败:', error)
        showToast({
            message: '查询书籍失败',
            type: 'fail'
        })
    } finally {
        docsLoading.value = false
    }
}

// 选择书籍
const handleSelectBook = (bookId: string) => {
    if (selectedBookId.value === bookId) return
    
    selectedBookId.value = bookId
    // 选中该书籍的第一个title
    const titles = booksData.value[bookId]
    if (titles && titles.length > 0) {
        const firstTitle = titles[0]
        if (firstTitle) {
            selectedTitle.value = firstTitle
            loadContent(bookId, firstTitle)
        }
    } else {
        selectedTitle.value = ''
        contentData.value = []
    }
}

// 选择标题
const handleSelectTitle = (title: string) => {
    if (selectedTitle.value === title) return
    
    selectedTitle.value = title
    if (selectedBookId.value) {
        loadContent(selectedBookId.value, title)
    }
}

// 加载内容
const loadContent = async (bookId: string, title: string) => {
    if (!bookId || !title) return
    
    docsLoading.value = true
    try {
        // bookId格式是b01, b02等,需要提取数字部分
        const bookIdNum = bookId.replace('b', '')
        const response = await docsApi.getContent(bookIdNum, title)
        
        if (response.data.error) {
            showToast({
                message: response.data.error,
                type: 'fail'
            })
            contentData.value = []
        } else {
            contentData.value = response.data.contents || []
        }
    } catch (error) {
        console.error('加载内容失败:', error)
        showToast({
            message: '加载内容失败',
            type: 'fail'
        })
        contentData.value = []
    } finally {
        docsLoading.value = false
    }
}

// 监听八字字符串变化,自动查询书籍
watch(baziString, (newBazi) => {
    if (newBazi && newBazi.length === 8 && Object.keys(booksData.value).length === 0) {
        queryBooks()
    }
}, { immediate: true })
</script>

<style scoped>
.docs-section {
    padding: 16px;
    background: #ffffff;
}

.docs-header {
    margin-bottom: 16px;
}

.docs-title {
    font-size: 18px;
    font-weight: 600;
    color: #4d4d4d;
    margin: 0;
}

.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px;
}

.empty-container {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 40px;
}

.empty-text {
    font-size: 14px;
    color: #94a3b8;
    text-align: center;
}
</style>
